package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.UserFreeze;
import com.tanhua.dubbo.api.mongo.UserFreezeApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ZacharyJo
 * @title: UserFreezeApiImpl
 * @projectName tanhua
 * @description
 * @date 2021/7/17 12:07:30
 */
@Service
public class UserFreezeApiImpl implements UserFreezeApi {
	@Autowired
	private MongoTemplate mongoTemplate;

	//冻结
	@Override
	public UserFreeze saveFreeze(UserFreeze userFreeze) {
		//获取userId
		Integer userId = userFreeze.getUserId();
		Query query = new Query(Criteria.where("userId").is(userId));
		query.with(Sort.by(Sort.Direction.DESC,"created"));
		UserFreeze user = mongoTemplate.findOne(query, UserFreeze.class);
		//如果user不存在（第一次封禁）
		if (user==null){
			userFreeze.setId(new ObjectId());
			userFreeze.setFreezeCreated(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
			userFreeze.setFreezeCount(1);
			mongoTemplate.save(userFreeze);
		}else {//(不是第一次封禁)
			Integer freezeCount = user.getFreezeCount();
			Update update = new Update();
			update.set("freezeCount", freezeCount++);
			update.set("freezingTime",userFreeze.getFreezingTime());
			update.set("freezingRange",userFreeze.getFreezingRange());
			update.set("reasonsForFreezing",userFreeze.getReasonsForFreezing());
			update.set("frozenRemarks",userFreeze.getFrozenRemarks());
			update.set("freezeCreated",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
			mongoTemplate.updateFirst(query, update,UserFreeze.class);
		}
		//讲修改过的日志返回出去
		return mongoTemplate.findOne(query,UserFreeze.class);
	}

	//解冻
	@Override
	public void unFreeze(Integer userId,String reasonsForThawing) {
		Query query = new Query(Criteria.where("userId").is(userId));
		Update update = new Update();
		//管理员解冻 入参userId reasonsForThawing
		update.set("unfreezeCreated",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		update.set("reasonsForThawing",reasonsForThawing);
		mongoTemplate.updateFirst(query,update,UserFreeze.class);
	}

}
